<?php
/**
 * @Author:      Michael(463343500@qq.com)
 * @DateTime:    2019-06-18 18:07:50
 * @Description: 基础model类
 */

namespace App\Model;


use App\Utility\Pool\MysqlPool;
use App\Utility\Pool\MysqlPoolObject;
use EasySwoole\Component\Pool\PoolManager;
use EasySwoole\EasySwoole\Config;

class BaseModel
{
    private $db;

    function __construct(MysqlPoolObject $db)
    {
        $this->db = $db;
    }

    protected function getDb(): MysqlPoolObject
    {
        return $this->db;
    }

    function getAll($condition = []): array
    {
        $allow = ['where', 'orWhere', 'join', 'orderBy', 'groupBy'];
        foreach ($condition as $k => $v) {
            if (in_array($k, $allow)) {
                foreach ($v as $item) {
                    $this->getDb()->$k(...$item);
                }
            }
        }
        $list = $this->getDb()
            ->get($this->table);
        return $list;
    }

    function update($condition = [], array $data)
    {
        $allow = ['where', 'orWhere', 'join', 'orderBy', 'groupBy'];
        foreach ($condition as $k => $v) {
            if (in_array($k, $allow)) {
                foreach ($v as $item) {
                    $this->getDb()->$k(...$item);
                }
            }
        }

        $this->getDb()->update($this->table, $data);
        return $this->getDb()->getAffectRows();
    }


    /**
     * [find 根据条件查询一条记录]
     * @param array $condition [查询条件]
     * @param  [type] $columns   [不填表示查询所有字段，如果为数组就查询指定字段]
     * @return [type]            [description]
     */
    public function find($condition = [], $columns = '*'): array
    {
        $allow = ['where', 'orWhere', 'join', 'orderBy', 'groupBy'];
        foreach ($condition as $k => $v) {
            if (in_array($k, $allow)) {
                foreach ($v as $item) {
                    $this->getDb()->$k(...$item);
                }
            }
        }
        $list = $this->getDb()
            ->getOne($this->table, $columns);
        $list = $list ? $list : [];
        return $list;
    }

    /**
     * [register 增加一条记录]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function register($data)
    {
        return $this->getDb()->insert($this->table, $data);
    }


    /**
     *获取图片服务器地址
     * @return string
     */
    public function getImgHost(): ?string
    {
        $conf = Config::getInstance()->getConf('IMG');
        $host = $conf['host'] . ":" . $conf['port'];
        return $host;
    }

}